﻿Imports ATS.HelperClass
Imports ATS.CommonClass
Imports ATS.EntryValidation


Partial Public Class ucPersons2
    Dim dbPersons As ATSDataClassesDataContext = New ATSDataClassesDataContext
    Private _pageIsValid As Boolean = True
    Dim editFlag As Integer
    Dim al As New ArrayList
    Dim comboDepartmentTextbox As TextBox

    Sub pageIsValid(ByVal sender As String, ByVal isValid As Boolean)
        Dim inArray As Boolean = False
        For i = 0 To al.Count - 1
            If al.Item(i) = sender Then
                If isValid Then
                    al.Remove(Trim(sender))
                End If
                inArray = True
                Exit For
            End If
        Next
        If Not inArray Then
            If Not isValid Then
                al.Add(Trim(sender))
            End If
        End If
        If al.Count > 0 Then
            _pageIsValid = False
        Else
            _pageIsValid = True
        End If
    End Sub

    Private Sub ucpersons_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        comboDepartmentTextbox = TryCast(comboboxDepartment.Template.FindName("PART_EditableTextBox", comboboxDepartment), TextBox)
        AddHandler comboDepartmentTextbox.TextChanged, AddressOf comboBoxDepartment_TextChanged
        LoadDepartments()
        editFlag = HelperClass.EditMode.Load
        Loadperson()
        DisableAllControls()
    End Sub

    Private Sub DisableAllControls()
        HelperClass.DisableTextBox(gridPersonDetails)
        HelperClass.DisablePasswordBox(gridPersonDetails)
        HelperClass.DisableCheckBox(gridPersonDetails)
        HelperClass.DisableComboBox(gridPersonDetails)
    End Sub
    Private Sub EnableAllControls()
        HelperClass.EnableTextBox(gridPersonDetails)
        HelperClass.EnablePasswordBox(gridPersonDetails)
        HelperClass.EnableCheckBox(gridPersonDetails)
        HelperClass.EnableComboBox(gridPersonDetails)
    End Sub
    Private Sub ClearAllControls()
        HelperClass.ClearTextBox(gridPersonDetails)
        HelperClass.ClearPasswordBox(gridPersonDetails)
        HelperClass.ClearCheckBox(gridPersonDetails)
        HelperClass.ClearComboBox(gridPersonDetails)
    End Sub

    Private Sub Loadperson(Optional ByVal userFilter As String = "")
        Dim personTable = From personDetails In dbPersons.Persons _
                         Where (personDetails.LastName & " " & personDetails.FirstName.ToUpper).Contains(userFilter.ToUpper) _
                         Order By personDetails.LastName & ", " & personDetails.FirstName.ToUpper _
                         Select personDetails _
                         , personName = Trim(personDetails.LastName & IIf(personDetails.LastName.Length > 0 And personDetails.FirstName.Length > 0, ", ", " ") & personDetails.FirstName.ToUpper) _
                         , departmentCode = personDetails.Department1.DepartmentCode _
                         , department = personDetails.Department1.DepartmentName _
                         , dateofBirth = personDetails.DateOfBirth




        listBoxPersons.ItemsSource = personTable
        listBoxPersons.SelectedIndex = 0
        If personTable.Count > 0 Then
            LoadFields(personTable)
            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
        Else
            ClearAllControls()
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
            'textboxCode.Text = Nothing
        End If
        If personTable.Count = 1 Then
            ExpanderText.Text = personTable.Count & " record found"
        Else
            ExpanderText.Text = personTable.Count & " records found"
        End If
    End Sub

    Private Sub LoadDepartments()
        Dim departmentTable = From departmentList In dbPersons.Departments _
                              Order By departmentList.DepartmentName

        comboboxDepartment.ItemsSource = departmentTable
        comboboxDepartment.SelectedValuePath = "DepartmentCode"
        comboboxDepartment.DisplayMemberPath = "DepartmentName"
    End Sub

    Private Sub LoadSelectedPerson(Optional ByVal PersonFilter As String = "")
        Dim personTable = From personDetails In dbPersons.Persons _
                         Where personDetails.EmployeeID = PersonFilter _
                         Order By personDetails.LastName & ", " & personDetails.FirstName.ToUpper _
                         Select personDetails _
                         , personName = Trim(personDetails.LastName & IIf(personDetails.LastName.Length > 0 And personDetails.FirstName.Length > 0, ", ", " ") & personDetails.FirstName.ToUpper) _
                         , departmentCode = personDetails.Department1.DepartmentCode _
                         , department = personDetails.Department1.DepartmentName _
                         , dateofBirth = personDetails.DateOfBirth
        '(personDetails.LastName & " " & personDetails.FirstName.ToUpper).Contains(PersonFilter.ToUpper) 
        If personTable.Count > 0 Then

            LoadFields(personTable)

            ucActions.buttonEditMain.IsEnabled = True
            ucActions.buttonDeleteMain.IsEnabled = True
        Else
            ClearAllControls()
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
            'textboxCode.Text = Nothing
        End If
    End Sub

    Private Sub LoadFields(ByVal personDetails As IQueryable)
        Dim lf = From perDetails In personDetails
        With lf.First
            textboxCode.Text = .personDetails.EmployeeID
            comboboxDepartment.SelectedValue = .departmentCode
            comboboxTitle.SelectedValue = .personDetails.Title
            textboxDesignation.Text = .personDetails.Designation
            textboxFirstName.Text = .personDetails.FirstName
            textboxLastName.Text = .personDetails.LastName
            textboxMiddleInitial.Text = .personDetails.MiddleInitial
            textboxExtensionNumber.Text = .personDetails.ExtensionNumber
            textboxEmailAddress.Text = .personDetails.EmailAddress
            comboboxGender.SelectedValue = .personDetails.Gender
            If .dateofBirth Is Nothing Then
                textboxBirthDate.SelectedDate = Nothing
                cbCalendar.IsChecked = False
            Else
                textboxBirthDate.SelectedDate = .dateofBirth
                cbCalendar.IsChecked = True
            End If

        End With
        pageIsValid(textboxCode.Name, EntryValidation.ValidateText(textboxCode))
        pageIsValid(textboxFirstName.Name, EntryValidation.ValidateText(textboxFirstName))
        pageIsValid(comboDepartmentTextbox.Name, ValidateEditableCombo(comboboxDepartment, comboDepartmentTextbox))
        pageIsValid(textboxLastName.Name, EntryValidation.ValidateText(textboxLastName))
    End Sub

    Private Sub listBoxpersons_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles listBoxPersons.SelectionChanged
        Dim selectedperson As String = ""
        If Not listBoxPersons.SelectedItem Is Nothing Then
            selectedperson = listBoxPersons.SelectedValue.persondetails.employeeid.ToString
        End If
        LoadSelectedPerson(selectedperson)
    End Sub

    Private Sub searchButton_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles searchButton.Click
        Loadperson(searchBox.Text)
    End Sub

    Private Sub searchBox_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles searchBox.TextChanged
        Loadperson(searchBox.Text)
    End Sub

    Private Sub ucActions_AddButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.AddButtonClicked
        gridListbox.IsEnabled = False
        editFlag = EditMode.Add
        ClearAllControls()
        EnableAllControls()
    End Sub

    Private Sub ucActions_CancelButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.CancelButtonClicked
        Dim selectedperson As String = ""
        If Not listBoxPersons.SelectedValue Is Nothing Then
            selectedperson = listBoxPersons.SelectedValue.persondetails.employeeid.ToString
        End If

        editFlag = EditMode.Load
        DisableAllControls()
        LoadSelectedPerson(selectedperson)
        gridListbox.IsEnabled = True
    End Sub

    Private Sub ucActions_DeleteButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.DeleteButtonClicked
        Try
            Dim warningString As String = "Do you really want to delete this record?" & ControlChars.Lf & ControlChars.Lf & listBoxPersons.SelectedItem.personname.ToString
            If System.Windows.MessageBox.Show(warningString, "Delete Record", MessageBoxButton.YesNo, MessageBoxImage.Warning) = MessageBoxResult.Yes Then
                Dim selectedpersonCode As String = listBoxPersons.SelectedValue.persondetails.employeeid.ToString
                Dim personsTable = From personDetails In dbPersons.Persons _
                             Where personDetails.EmployeeID.ToUpper = (selectedpersonCode.ToUpper)
                Dim exst As Person = personsTable.First
                dbPersons.Persons.DeleteOnSubmit(exst)
                dbPersons.SubmitChanges()
                Loadperson()
            End If
        Catch ex As Exception
            CheckForSQLErrors(ex)
        End Try
    End Sub

    Private Sub ucActions_EditButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.EditButtonClicked
        editFlag = EditMode.Edit
        gridListbox.IsEnabled = False
        EnableAllControls()
        textboxCode.IsEnabled = False
    End Sub

    Private Sub ucActions_SaveButtonClicked(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles ucActions.SaveButtonClicked
        Try
            If _pageIsValid Then
                Dim ListBoxSelectedItemIndex As Integer = listBoxPersons.SelectedIndex
                Dim departmentTable = From departmentDetails In dbPersons.Departments.Where(Function(p) p.DepartmentName = comboboxDepartment.Text)
                If departmentTable.Count = 0 Then
                    Dim departmentDetails As New Department
                    With departmentDetails
                        .DepartmentName = comboboxDepartment.Text
                        .DepartmentCode = comboboxDepartment.Text
                    End With
                    dbPersons.Departments.InsertOnSubmit(departmentDetails)
                End If

                If editFlag = EditMode.Edit Then
                    Dim personsTable = From personDetails In dbPersons.Persons _
                                 Where personDetails.EmployeeID = textboxCode.Text.ToUpper

                    With personsTable.First
                        If comboboxDepartment.SelectedIndex < 0 Then
                            .Department = comboboxDepartment.Text
                        Else
                            .Department = comboboxDepartment.SelectedValue
                        End If
                        .Title = comboboxTitle.SelectedValue
                        .Designation = textboxDesignation.Text
                        .FirstName = textboxFirstName.Text
                        .LastName = textboxLastName.Text
                        .MiddleInitial = textboxMiddleInitial.Text
                        .ExtensionNumber = textboxExtensionNumber.Text
                        .EmailAddress = textboxEmailAddress.Text
                        .Gender = comboboxGender.SelectedValue
                        If cbCalendar.IsChecked Then
                            .DateOfBirth = textboxBirthDate.Text
                        Else
                            .DateOfBirth = Nothing
                        End If

                    End With
                ElseIf editFlag = EditMode.Add Then
                    Dim saveNewperson As New Person
                    With saveNewperson
                        .EmployeeID = textboxCode.Text
                        If comboboxDepartment.SelectedIndex < 0 Then
                            .Department = comboboxDepartment.Text
                        Else
                            .Department = comboboxDepartment.SelectedValue
                        End If
                        .Title = comboboxTitle.SelectedValue
                        .Designation = textboxDesignation.Text
                        .FirstName = textboxFirstName.Text
                        .LastName = textboxLastName.Text
                        .MiddleInitial = textboxMiddleInitial.Text
                        .ExtensionNumber = textboxExtensionNumber.Text
                        .EmailAddress = textboxEmailAddress.Text
                        .Gender = comboboxGender.SelectedValue
                        If cbCalendar.IsChecked Then
                            .DateOfBirth = textboxBirthDate.Text
                        Else
                            .DateOfBirth = Nothing
                        End If
                    End With
                    dbPersons.Persons.InsertOnSubmit(saveNewperson)
                End If
                dbPersons.SubmitChanges()
                LoadDepartments()
                editFlag = EditMode.Load
                If searchBox.Text.Length > 0 Then
                    Loadperson(searchBox.Text)
                Else
                    Loadperson()
                End If

                listBoxPersons.SelectedIndex = ListBoxSelectedItemIndex
                DisableAllControls()
                gridListbox.IsEnabled = True
                _pageIsValid = True
            Else
                ucActions.buttonSaveMain.IsEnabled = True
                ucActions.buttonEditMain.IsEnabled = False
                ucActions.buttonAddMain.IsEnabled = False
                ucActions.buttonDeleteMain.IsEnabled = False
                ucActions.buttonCancelMain.IsEnabled = True
                Dim warningString As String = "Some mandatory fields are missing."
                System.Windows.MessageBox.Show(warningString, "Missing entry", MessageBoxButton.OK, MessageBoxImage.Information)
            End If
        Catch ex As Exception
            CheckForSQLErrors(ex)
            ucActions.buttonSaveMain.IsEnabled = True
            ucActions.buttonEditMain.IsEnabled = False
            ucActions.buttonAddMain.IsEnabled = False
            ucActions.buttonDeleteMain.IsEnabled = False
            ucActions.buttonCancelMain.IsEnabled = True
        End Try
    End Sub

    Private Sub textboxCode_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxCode.TextChanged
        pageIsValid(sender.name, EntryValidation.ValidateText(sender))
        If editFlag = EditMode.Add Then
            Dim selectedperson As String = textboxCode.Text.ToString
            Dim personTable = From personDetails In dbPersons.Persons _
                         Where personDetails.EmployeeID = selectedperson.ToUpper
            If personTable.Count > 0 And textboxCode.IsEnabled = True Then
                _pageIsValid = False
                textboxCode.BorderBrush = New SolidColorBrush(Colors.Red)
                textboxCode.ToolTip = "Employee Id already exist."
            End If
        End If
    End Sub

    Private Sub textboxName_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxFirstName.TextChanged
        pageIsValid(sender.name, EntryValidation.ValidateText(sender))
    End Sub

    Private Sub comboBoxDepartment_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs)
        comboDepartmentTextbox.Text = comboboxDepartment.Text
        pageIsValid(sender.name, ValidateEditableCombo(comboboxDepartment, comboDepartmentTextbox))
    End Sub

    Private Sub textboxLastName_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textboxLastName.TextChanged
        pageIsValid(sender.name, EntryValidation.ValidateText(sender))

    End Sub

    Private Sub cbCalendar_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles cbCalendar.Checked, cbCalendar.Unchecked
        If cbCalendar.IsChecked And cbCalendar.IsEnabled Then
            textboxBirthDate.IsEnabled = True
            pageIsValid(textboxBirthDate.Name, EntryValidation.ValidateDatePicker(textboxBirthDate))
        Else
            textboxBirthDate.ClearValue(ComboBox.BorderBrushProperty)
            pageIsValid(textboxBirthDate.Name, True)
            textboxBirthDate.IsEnabled = False
        End If
    End Sub

    Private Sub textboxBirthDate_SelectedDateChanged1(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles textboxBirthDate.SelectedDateChanged
        pageIsValid(sender.Name, EntryValidation.ValidateDatePicker(sender))
    End Sub
End Class
